﻿/// <reference path="../jquery-3.4.1.min.js" />
/// <reference path="../common.js" />

function initUpload(fileExtStr, browseButtonId, fnBeforeUploadCallback, fnCompleteCallback) {
    var myuploader = SetPlUpload(fileExtStr, browseButtonId, 'filelist', 'file_container', 'file_Block', false, 'imgListShow', false, fnBeforeUploadCallback, fnCompleteCallback);
    myuploader.init();
    return myuploader;
}

function SetPlUpload(fileExtStr, browseButtonId, fileQueueId, containerId, fileShowContainerId, canSelectMulti, showImgContainer, canDisplayMulti, fnBeforeUploadCallback, fnCompleteCallback) {
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: browseButtonId, //'pickfiles', // you can pass an id...
        multi_selection: canSelectMulti == true || canSelectMulti == false ? canSelectMulti : true,
        container: document.getElementById(containerId), // ... or DOM Element itself
        //url: 'upload.php',
        url: '/admin/handler/uploadFile.ashx',
        flash_swf_url: '/js/plupload/Moxie.swf',
        silverlight_xap_url: '/js/plupload/Moxie.xap',
        //multipart_params: { 'customWidth': (smallPicWidth == undefined || smallPicWidth == null || smallPicWidth == '' ? 0 : smallPicWidth), 'customHeight': (smallPicHeight == undefined || smallPicHeight == null || smallPicHeight == '' ? 0 : smallPicHeight), 'extType': fileExtStr },
        filters: {
            max_file_size: '10mb',
            mime_types: [
                { title: "允许上传的文件", extensions: fileExtStr }// "jpg,gif,png,zip,rar,mp4,avi,rmvb"
            ]
        },

        init: {
            PostInit: function () {
                top.document.getElementById(fileQueueId).innerHTML = '';//'filelist'
                document.getElementById(containerId).style.display = 'none';
                //document.getElementById('uploadfiles').onclick = function () {
                //    uploader.start();
                //    return false;
                //};
            },

            BeforeUpload: function (uploader, file) {
                if (typeof (fnBeforeUploadCallback) == 'function') {
                    fnBeforeUploadCallback(uploader, file);
                }
            },

            FilesAdded: function (up, files) {
                var v_html = '';
                plupload.each(files, function (file) {

                    v_html += '<div id=' + file.id + ' class="uploaditem">'
                                    + '<p>' + file.name + '(' + plupload.formatSize(file.size) + ')</p>'
                                    + '<div class="progressbar">'
                                        + '<div class="barpercent"></div>'
                                    + '</div>'
                                    + '<div class="barpercentShow">0%</div>'
                                + '</div>';
                });

                top.document.getElementById(fileQueueId).innerHTML = v_html;//'filelist'
                uploader.ShowUploadDialog();
                uploader.start();
            },

            UploadProgress: function (up, file) {
                top.$('#' + file.id).find('.barpercentShow').text(file.percent + '%');
                top.$('#' + file.id).find('.barpercent').width(top.$('#' + file.id).find('.progressbar').width() * file.percent / 100);
            },
            UploadComplete: function (up, files) {
                top.sysAlert.success('上传成功');
                //bindAttachmentImageShow(uploader);
                uploader.CloseUploadDialog();

                if (typeof (fnCompleteCallback) == 'function') {
                    fnCompleteCallback();
                }
            },

            Error: function (up, err) {
                top.sysAlert.Error(err.message);
            },

            FileUploaded: function (uploader, file, responseObject) {
                var retobj = $.parseJSON(responseObject.response);
                if (uploader.multi_selection) {
                    uploader.attachmentList.push(retobj.data);
                }
                else {
                    uploader.attachmentList = [];
                    uploader.attachmentList.push(retobj.data);
                }
                //console.log(retobj);
                
            }
        }
    });

    //var containerHtml = "<div id=\"file_container\" class=\"noshow\"></div><div id=\"file_Block\"><ul class=\"upload-img\"></ul><ul class=\"upload-list\"></ul></div>";
    //if ($('#file_container').length == 0) {
    //    $('body').append(containerHtml);
    //}

    uploader.attachmentList = [];

    uploader.SetReadOnly = function () {
        $('#' + uploader.FileListId).find('.upload-remove,.upload-img-remove').remove();
    }

    uploader.ShowUploadDialog = function () {
        var v_width = top.$('div.uploadDialog').width();
        var v_height = document.body.clientHeight; // top.$('div.uploadDialog').height();
        top.$('div.uploadDialog').css({ 'left': (top.$(top.window).width() / 2 - v_width / 2) + 'px', 'top': '30%' });
        top.$('div.shadow').width(top.$(top.window).width());
        top.$('div.shadow').height(top.$(top.window).height());
        top.$('div.shadow').show();
        top.$('div.uploadDialog').show();
    }
    uploader.CloseUploadDialog = function () {
        top.$('div.shadow').hide();
        top.$('div.uploadDialog').hide();
    }
    uploader.GetAttchmentArr = function () {
        return $('#' + fileShowContainerId).getAllAttchment();
    }
    uploader.LoadData = function (lst, isReadOnly) {
        if (lst) {
            var pichtml = '';
            var otherhtml = '';

            var v_inlineStyle = smallPicWidth > 0 && smallPicHeight > 0 ? ' style="width:' + smallPicWidth + 'px;height:' + smallPicHeight + 'px;"' : '';

            for (var i = 0; i < lst.length; i++) {
                v_data = lst[i];
                v_data.ext = /\.[^\.]+/.exec(v_data.orname);

                if (v_data.ext == '.jpg' || v_data.ext == '.jpeg' || v_data.ext == '.bmp' || v_data.ext == '.png' || v_data.ext == '.gif') {//如果是图片
                    pichtml += '<li id="' + v_data.mid + '" url="' + v_data.url + '" orname="' + v_data.orname + '" aid="' + v_data.aid + '" >'
                            + '<img src="' + v_data.url + '" ' + v_inlineStyle + ' class="AttachmentImage" />'
                            + '<p class="upload-img-name">' + v_data.orname + '</p>'
                            + '<a class="upload-img-remove" onclick="_deleteAttachmentItem(this)"></a>'
                        + '</li>';
                }
                else {//如果不是图片

                    //分支判断需要加载的图标类型
                    var iconClass = 'i-word';
                    if (v_data.ext == '.doc' || v_data.ext == '.docx') {
                        iconClass = 'i-word';
                    }
                    else if (v_data.ext == '.pdf') {
                        iconClass = 'i-pdf';
                    }
                    else if (v_data.ext == '.txt') {
                        iconClass = 'i-txt';
                    }
                    else if (v_data.ext == '.ppt' || v_data.ext == '.pptx') {
                        iconClass = 'i-ppt';
                    }
                    else if (v_data.ext == '.xls' || v_data.ext == '.xlsx') {
                        iconClass = 'i-excel';
                    }
                    else if (v_data.ext == '.rar' || v_data.ext == '.zip') {
                        iconClass = 'i-zip';
                    }
                    else {
                        iconClass = 'i-other';
                    }

                    otherhtml += '<li id="' + v_data.mid + '" url="' + v_data.url + '" orname="' + v_data.orname + '" aid="' + v_data.aid + '" >'
                                + '<p class="i-upload1 ' + iconClass + '"></p>'
                                + '<span>' + v_data.orname + '</span>'
                                + '<span class="upload-btn">'
                                    + '<a  class="i-upload1 upload-remove" onclick="_deleteAttachmentItem(this)"></a>'
                                    + '<a href="' + v_data.url + '" class="i-upload1 upload-down"></a>'
                                + '</span>'
                            + '</li>';
                }
            }

            if (uploader.canDisplayMulti) {
                $('#' + uploader.FileListId).find('ul.upload-img').append(pichtml);
                $('#' + uploader.FileListId).find('ul.upload-list').append(otherhtml);
            }
            else {
                $('#' + uploader.FileListId).find('ul.upload-img').html(pichtml);
                $('#' + uploader.FileListId).find('ul.upload-list').html(otherhtml);
            }

            bindAttachmentImageShow(uploader);

            if (isReadOnly == '1') {
                uploader.SetReadOnly();
            }
        }
    }

    uploader.GetImgListData = function () {
        var arr = [];
        $('#' + uploader.FileListId).find('ul.upload-img').find('li').each(function () {
            var v_title = $(this).attr('orname');
            var v_url = $(this).attr('url');
            var tmp = { title: v_title, url: v_url };
            arr.push(tmp);
        });

        return arr;
    }

    uploader.FileListId = fileShowContainerId;
    uploader.canDisplayMulti = canDisplayMulti == true || canDisplayMulti == false ? canDisplayMulti : true;

    return uploader;
}

function MakeImageList(containerId, imgWidth, imgHeight) {
    var __imglistBlock = {
        listid: containerId,
        picWidth: imgWidth,
        picHeight: imgHeight,
        init: function () {
            var _self = top.$('#' + this.listid);
            var v_html = '<div class="imgArrow">'
                           + '<a class="arrow prev" href="javascript:void(0)"></a>'
                           + '<a class="arrow next" href="javascript:void(0)"></a>'
                           + '<a class="arrow close" href="javascript:void(0)"></a>'
                        + '</div>'
                        + '<div class="imgList">'
                        + '</div>';
            top.$('#' + this.listid).html(v_html);

            //绑定事件
            _self.find('.imgArrow').hover(
                function () {
                    $(this).find('a.arrow').css('display', 'block');
                }
                ,
                function () {
                    $(this).find('a.arrow').css('display', 'none');
                });
            _self.find('a.prev').click(function () {
                _self.find('.imgWapper.active').fadeOut(200, function () {
                    $(this).removeClass('active');
                    var nextobj = $(this).is(':first-child') ? $(this).siblings().last() : $(this).prev();

                    if ($(this).is(':first-child') && $(this).is(':last-child')) {
                        nextobj = $(this);
                    }

                    nextobj.fadeIn(200).addClass('active');
                    nextobj.css('display', 'table-cell');
                    _self.find('.imgTitle').text(nextobj.find('img').prop('title'));
                });
            });
            _self.find('a.next').click(function () {
                _self.find('.imgWapper.active').fadeOut(200, function () {
                    $(this).removeClass('active');
                    var nextobj = $(this).is(':last-child') ? $(this).siblings().first() : $(this).next();

                    if ($(this).is(':first-child') && $(this).is(':last-child')) {
                        nextobj = $(this);
                    }

                    nextobj.fadeIn(200).addClass('active');
                    nextobj.css('display', 'table-cell');
                    _self.find('.imgTitle').text(nextobj.find('img').prop('title'));
                });
            });
            _self.find('a.close').click(function () {
                top.$('.shadow').hide();
                _self.hide();
            });

        },
        loadData: function (imgDataArr) {
            var _self = top.$('#' + this.listid);
            var v_html = '';
            for (var i = 0; i < imgDataArr.length; i++) {
                var ro = imgDataArr[i];
                //var vvClass = i == 0 ? 'active' : '';
                v_html += '<div class="imgWapper">'
                				+ '<div class="imgCon">'
                                + '<img title="' + ro.title + '" src="' + ro.url + '" onload="imgload(this,' + this.picWidth + ',' + this.picHeight + ')" />'
                           		+ '<div class="imgTitle">' + ro.title + '</div>'
                           		+ '</div>'
                           + '</div>';
            }
            //_self.find('.imgTitle').text(imgDataArr[0].title);
            _self.find('div.imgList').html(v_html);
            this.resize(this.picWidth, this.picHeight);
        },
        resize: function (imgWidth, imgHeight) {
            var _self = top.$('#' + this.listid);
            this.picWidth = imgWidth;
            this.picHeight = imgHeight;
            //最外层框大小
            _self.width(imgWidth);
            _self.height(imgHeight);

            //箭头遮罩层
            _self.find('.imgArrow').width(imgWidth);
            _self.find('.imgArrow').height(imgHeight);

            //每张图片大小
            _self.find('.imgWapper').width(imgWidth);
            _self.find('.imgWapper').height(imgHeight);

            //标题大小
            //          _self.find('.imgTitle').width(imgWidth - 2);
            //
            _self.find('.imgList').width(imgWidth).height(imgHeight);
        },
        showList: function (startIndex) {
            var _self = top.$('#' + this.listid);

            _self.find('div.imgWapper').remove('active');
            _self.find('div.imgWapper').eq(startIndex).addClass('active');

            _self.find('.imgTitle').text(_self.find('div.imgWapper').eq(startIndex).find('img').attr('title'));
            var v_left = ($(window.top).width() - _self.width()) / 2;
            var v_top = ($(window.top).height() - _self.height()) / 2;
            _self.parent().css({ top: v_top + 'px', left: v_left + 'px' });
            top.$('.shadow').show();
            top.$('.shadow').css({ width: '100%', height: '100%' });
            _self.show();
        },
        closeList: function () {
            var _self = $('#' + this.listid);
            top.$('.shadow').hide();
            _self.hide();
        }
    };

    return __imglistBlock;
}

function bindAttachmentImageShow(v_uploader) {

    $('img.AttachmentImage').unbind('click').click(function () {
        var v_startindex = $(this).parent().index();

        var imgListData = v_uploader.GetImgListData();
        //console.log(JSON.stringify(imgListData));
        v_uploader.showImgObj.loadData(imgListData);
        v_uploader.showImgObj.showList(v_startindex);
    });
}



